﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using tools_library;
using System.Net;
using System.Net.Sockets;

namespace rclient
{
    public partial class frmController : Form
    {
        //string RemoteHost;
        //int RemotePort;
        IPEndPoint RemoteEp;
        int LocalPort = 2033;
        NetworkTool service = new NetworkTool();
        HelperTool Helper = new HelperTool();
        public bool ViewOnly;
        
        public frmController()
        {
            InitializeComponent();
        }

        public frmController(IPEndPoint ep, bool viewOnly)
        {
            this.RemoteEp = ep;
            this.ViewOnly = viewOnly;
            //this.RemotePort = remotePort;
            InitializeComponent();
            service.StartServer(LocalPort, new NetworkTool.MessageReceivedDelegate(OnMessageReceived), (ISynchronizeInvoke)this);
        }

        private void OnMessageReceived(object sender, MessageReceivedArgs e)
        {
            switch (e.Command)
            { 
                case "$screen":
                    byte[] bytes = Convert.FromBase64String(e.Body);
                    Bitmap newbitmap = Helper.ByteToBitmap(bytes);
                    pictureBox1.Image = Image.FromHbitmap(newbitmap.GetHbitmap());
                    break;
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            frmController_Resize(null, null);
            this.Text += RemoteEp.Address.ToString() + ":" + RemoteEp.Port.ToString();
            StartRemoteSession();
        }

        private void frmController_Resize(object sender, EventArgs e)
        {
            pictureBox1.Size = this.Size;
        }

        private void StartRemoteSession()
        {
            Node node = new Node(RemoteEp);
            if (!ViewOnly)
            {
                service.SendMessage(node, "$startcontrol", "");
            }
            else
            {
                service.SendMessage(node, "$startview", "");
            }
        }

        private void frmController_FormClosed(object sender, FormClosedEventArgs e)
        {
            service.BroadcastMessage("$stopcontrol", "");
            service.StopServer();
        }
    }
}
